library(igraph)

x = A[which(A$A.A7_Area.Neighborhood == 'Bangalore 109'),]

adj_mat = matrix(nrow = nrow(x) + length(s(x$L.L50_Neighborhood.Leader)),
                 ncol = nrow(x) + length(s(x$L.L50_Neighborhood.Leader)))

#function to make network graphs for leaders (from household data)
leader_adj = function(x){
  
  leaders = levels(factor(x$L.L50_Neighborhood.Leader))
  n_leader = length(leaders)
  
  adj_mat = matrix(nrow = nrow(x) + n_leader,
                   ncol = nrow(x) + n_leader)
  
  adj_mat[1:n_leader,] = 0 #fill in 0's for leaders
  
  ind = n_leader#start after leader rows 
  for(i in 1:n_leader){ #index over leades
    n_follow = sum(x$L.L50_Neighborhood.Leader == leaders[i], na.rm = T )
    adj_mat[ind+(1:n_follow),i] = 1 #fill in 1 for ith column of rows corresponding to that person's followers
    ind = ind + n_follow
    }
  return(adj_mat)
}

tmat = leader_adj(x)

tgr = graph_from_adjacency_matrix(tmat, mode = c("directed"), weighted = NULL, diag = TRUE)
V(tgr)$Neighborhood = as.character(x$A.A7_Area.Neighborhood[1])

plot.igraph(tgr,vertex.size=8,vertex.label = NA,edge.arrow.size=0.2, edge.width=1, edge.lty=1,
            margin = 0.1, main = V(tgr)$Neighborhood[1])

gr_pl = function(x){
  tmat = leader_adj(x)
  tgr = graph_from_adjacency_matrix(tmat, mode = c("directed"), weighted = NULL, diag = TRUE)
  V(tgr)$Neighborhood = as.character(x$A.A7_Area.Neighborhood[1])
  
  plot.igraph(tgr,vertex.size=8,vertex.label = NA,edge.arrow.size=0.2, edge.width=1, edge.lty=1,
              margin = 0.1)
  }

gr_pl(x = A[which(A$A.A7_Area.Neighborhood == 'Bangalore 109'),])

#Figure 2 in paper
jpeg(paste0('../results/Fig2_',(Sys.time() %>% str_replace_all(c(":" = "-", " " = "_"))),'.jpg'))
par(mfrow=c(2,2),mar=c(1, 1, 1, 1) + 0.1)#it goes c(bottom, left, top, right))
gr_pl(x = A[which(A$A.A7_Area.Neighborhood == 'Bangalore 109'),]);box()
gr_pl(x = A[which(A$A.A7_Area.Neighborhood == 'Venkatraman Nagar'),]);box()
gr_pl(x = A[which(A$A.A7_Area.Neighborhood == 'Vivekananda Vasanthi Sankeerna'),]);box()
gr_pl(x = A[which(A$A.A7_Area.Neighborhood == 'Uttarahalli'),]);box()
dev.off()